<!--
  文件描述：样品点检追溯
  创建时间：2023/7/13 14:25
  创建人：LiCY
-->
<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <a-spin :spinning="confirmLoading">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="4" :sm="4">
              <a-form-item label="样本号">
                <!--                <j-popup-->
                <!--                  placeholder="请选择样本号"-->
                <!--                  v-model="spcParameter.description"-->
                <!--                  field="description"-->
                <!--                  org-fields="cfgid,description,save_typ,spc_typ,usl,lsl"-->
                <!--                  dest-fields="redId,description,saveTyp,spcTyp,usl,lsl"-->
                <!--                  code="spc_cfg"-->
                <!--                  :multi="true"-->
                <!--                  :triggerChange="true"-->
                <!--                  @callback="popupCallback"-->
                <!--                />-->
                <a-input placeholder="请输入样本号" v-model="queryParam.unitsn"></a-input>
                <!--                <a-input @click="openModal" placeholder="请输入样本号" v-model="showText" readOnly :disabled="disabled">-->
                <!--                  <a-icon slot="prefix" type="cluster" :title="title" />-->
                <!--                  <a-icon v-if="showText" slot="suffix" type="close-circle" @click="handleEmpty" title="清空" />-->
                <!--                </a-input>-->
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="7" :md="4" :sm="4">
              <a-form-item label="开始时间">
                <j-date placeholder="开始时间" v-model="queryParam.sTime" :showTime="true"
                        dateFormat="YYYY-MM-DD HH:mm:ss" />
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="7" :md="4" :sm="4">
              <a-form-item label="结束时间">
                <j-date placeholder="结束时间" v-model="queryParam.eTime" :showTime="true"
                        dateFormat="YYYY-MM-DD HH:mm:ss" />
              </a-form-item>
            </a-col>
            <!--            <a-col :xl="6" :lg="7" :md="4" :sm="4">-->
            <!--              <a-form-item label="分析参数">-->
            <!--                <a-input placeholder="请输入分析参数" v-model="queryParam.recId"></a-input>-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->
            <a-col :xl="6" :lg="7" :md="4" :sm="4">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="loadData" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="exportXls('产品主数据')" style="margin-left: 8px">导出</a-button>
              <!--              <a-button type="primary" icon="download" style="margin-left: 8px" @click="exportXls('样品点检追溯导出')">导出</a-button>-->
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->
      <!-- table区域-begin -->
      <a-row :gutter="10">
        <a-col :md="18" :sm="24" style="margin-bottom: 20px">
          <div>
            <a-table
              ref="table"
              size="middle"
              style="{ wordBreak:'break-all'}"
              class="j-table-force-nowrap"
              :scroll="{x:true}"
              bordered
              rowKey="recId"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :loading="loading"
              :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type:'radio'}"
              :customRow="clickThenSelect"
              @change="handleTableChange">
            </a-table>
          </div>
        </a-col>
        <a-col :md="6" :sm="24">
          <div>
            <a-table
              ref="table"
              size="middle"
              style="{ wordBreak:'break-all'}"
              class="j-table-force-nowrap"
              :scroll="{x:true}"
              bordered
              rowKey="dataid"
              :columns="columns2"
              :dataSource="dataSource2"
              :loading="loading2">
            </a-table>
          </div>
        </a-col>
      </a-row>
      <!--      <a-tabs v-show="isChart">-->
      <!--        <a-tab-pane key="1" tab="control chart">-->
      <!--          <div id="valueTrend" style="height:30vh;width: 100%;"></div>-->
      <!--        </a-tab-pane>-->
      <!--        <a-tab-pane key="2" tab="range chart">-->
      <!--          <div id="rangeTrend" style="height:30vh;width: 100%;background-color: #2fc437"></div>-->
      <!--        </a-tab-pane>-->
      <!--      </a-tabs>-->
    </a-spin>
    <sample-modal :visible="visible" @close="modalClose"></sample-modal>
  </a-card>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
// 例如：import uploadFile from '@/components/uploadFile/uploadFile'
import SampleModal from '@/components/modal/SampleModal.vue'
import { downFile, getAction, postAction } from '@api/manage'
// 例如：import uploadFile from '@/components/uploadFile/uploadFile'
let echarts = require('echarts')

export default {
  name: 'SampleTrace',
  // import引入的组件需要注入到对象中才能使用
  components: {
    SampleModal
  },
  props: {},
  watch: {
    recId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.loadProcData(val)
        }
      }
    }
  },
  data() {
    // 这里存放数据
    return {
      disabled: false,
      title: '',
      showText: '',
      visible: false,
      isChart: false,
      confirmLoading: false,
      spcParameter: {},
      queryParam: {},
      procQueryParam: {},
      recId: '',
      loading: false,
      loading2: false,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '产线',
          align: 'center',
          dataIndex: 'line'
        },
        {
          title: '工站',
          align: 'center',
          dataIndex: 'op'
        },
        {
          title: '序列号',
          align: 'center',
          dataIndex: 'unitsn'
        },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'shift'
        },
        {
          title: '加工时间',
          align: 'center',
          dataIndex: 'ctime'
        },
        {
          title: '点检结果',
          align: 'center',
          dataIndex: 'result',
          customRender: function(text) {
            if (text === '1') {
              return 'OK'
            } else if (text === '2') {
              return 'NG'
            } else {
              return text
            }
          }
        }
      ],
      columns2: [
        {
          title: '参数描述',
          align: 'center',
          dataIndex: 'dataid_dictText'
        },
        {
          title: '值',
          align: 'center',
          dataIndex: 'value'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText'
        },
        {
          title: '下限',
          align: 'center',
          dataIndex: 'lowLimit'
        },
        {
          title: '上限',
          align: 'center',
          dataIndex: 'upLimit'
        }
      ],
      /* 数据源 */
      dataSource: [],
      dataSource2: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/trace/sampleTrace/list',
        getProcList: '/trace/barcodeTrace/listMesProcDataValueByMainId',
        getChartInfo: '/qis/spc/getSampleChartInfo',
        exportXlsUrl: '/trace/sampleTrace/exportXls'
      },
      spcData: {},
      valueTrendChart: {},
      valueTrendOption: {},
      rangeTrendChart: {},
      rangeTrendOption: {},
      rangeValues: [],
      controlValues: [],
      line: [],
      uclR: 0,
      clX: 0,
      lclR: 0,
      uclX: 0,
      lclX: 0,
      selectedRowKeys: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 方法集合
  methods: {
    modalClose() {
      this.visible = false
    },
    close() {
      this.visible = false
    },
    destroyOnClose() {
    },
    handleCancel() {
      this.close()
    },
    handleOk() {
      this.close()
    },
    openModal() {
      this.visible = true
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.recId = record.recId
            this.onSelectChange(record.recId.split(','), [record])
          }
        }
      }
    },
    searchQuery() {

    },
    getChartInfo() {
      if (this.queryParam.unitsn) {
        //根据cfgid和样本序列号查询spc控制图数据
        postAction(this.url.getChartInfo, this.queryParam).then((res) => {
          if (res.code === 200) {
            console.log('样本SPC返回值')
            console.log(res)
            this.createData(res.result)
            // this.spcData = res.result
            // let rangeValues = []
            // let controlValues = []
            // this.spcData.rangeValues.map(item => {
            //   rangeValues.push([item.name + '', item.value, item.id, item.color])
            // })
            // this.spcData.controlValues.map(item => {
            //   controlValues.push([item.name + '', item.value, item.id, item.color])
            // })
            // this.uclR = this.spcData.uclR
            // this.lclR = this.spcData.lclR
            // this.uclX = this.spcData.uclX
            // this.lclX = this.spcData.lclX
            //
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      }

    },
    onClearSelected() {
      this.selectedRowKeys = []
    },
    loadProcData(val) {
      //查询对应加工历史的具体参数
      getAction(this.url.getProcList, { mainId: this.recId }).then(res => {
        this.dataSource2 = res.result.records
      })
    },
    loadData(arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.onClearSelected()
      var param = this.queryParam
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      this.loading = true
      getAction(this.url.list, param).then((res) => {
        if (res.success) {
          this.dataSource = res.result.historyList.records
          this.ipagination.total = res.result.historyList.total
          this.getChartInfo()
          this.isChart = true
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })

    },
    searchReset() {
    },
    exportXls(fileName) {
      this.loading = true
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      downFile(this.url.exportXlsUrl, this.queryParam).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      }).finally(() => {
        this.loading = false
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectionRows[0].recId
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    chartInit() {
      this.valueTrendChart = echarts.init(document.getElementById('valueTrend'))
      // this.rangeTrendChart = echarts.init(document.getElementById('rangeTrend'))
    },
    handleWindowResize() {
      this.valueTrendChart.resize()
      // this.rangeTrendChart.resize()
    },
    createData(val) {
      let controlValues = []
      val.controlValues.map(item => {
        controlValues.push([item.name + '', item.value, item.id, item.color])
      })
      this.line = [{
        name: 'uclX',
        value: val.uclX
      }, {
        name: 'lclX',
        value: val.lclX
      }, {
        name: 'clX',
        value: val.clX
      }
      ]
      this.controlValues = controlValues
      this.uclX = val.uclX
      this.lclX = val.lclX
      this.clX = val.clX
      this.initValueTrendChart()
    },
    /**
     * 初始化控制图
     */
    initValueTrendChart() {
      let that = this
      let lclX = that.lclX
      let clX = that.clX
      let uclX = that.uclX
      let startLength = 100 - (50 / that.controlValues.length * 100)
      // 指定图表的配置项和数据
      this.valueTrendOption = {
        tooltip: {
          trigger: 'axis',
          transitionDuration: 0,  //鼠标移入抖动
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          position: 'left'
        },
        title: {
          left: 'left',
          text: 'control chart'
        },
        grid: {
          left: '4%',
          right: '4%'
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          splitLine: {
            show: false
          },
          min: function(e) {
            return (lclX - lclX * 0.05).toFixed(4)
          },
          max: function(e) {
            return (uclX + uclX * 0.05).toFixed(4)
          }
        },

        dataZoom: [
          {
            type: 'inside',
            start: startLength,
            end: 100
          },
          {
            start: 0,
            end: 20
          }
        ],
        series: [
          {
            name: 'Data',
            type: 'line',
            data: this.controlValues,
            itemStyle: {
              normal: {
                color: function(seriesIndex) { //拐点颜色回调
                  let val = seriesIndex.data[1]
                  if (val > uclX || val < lclX) {
                    return 'yellow'
                  } else {
                    return 'green'
                  }
                },
                lineStyle: {
                  color: 'green'
                }
              }
            },
            markLine: {
              symbol: 'none',//去掉箭头
              silent: true,
              data: this.line.map(function(item) {
                if (item.name === 'clX') {
                  return {
                    yAxis: item.value.toFixed(4),
                    lineStyle: {
                      width: 2,
                      color: 'blue',
                      type: 'dotted'
                    }
                  }
                } else {
                  return {
                    yAxis: item.value.toFixed(4),
                    lineStyle: {
                      width: 2,
                      color: 'black',
                      type: 'dotted'
                    }
                  }
                }
              })
            }
          }
        ]
      }
      // 使用刚指定的配置项和数据显示图表。
      this.valueTrendOption && this.valueTrendChart.setOption(this.valueTrendOption)
      const myEvent = new Event('resize')
      window.dispatchEvent(myEvent)
    }
  },
  // 监控data中的数据变化
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.chartInit()
    window.addEventListener('resize', this.handleWindowResize)
  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style scoped>
@import '~@assets/less/common.less';
</style>
